package com.wanbatv.wanba.ahitv.view;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.wanbatv.wanba.ahitv.R;
import com.wanbatv.wanba.ahitv.activity.AlbumFullScreenActivity;
import com.wanbatv.wanba.ahitv.util.BitmapCache;
import com.wanbatv.wanba.ahitv.util.FocusImageView;
import com.wanbatv.wanba.ahitv.util.Util;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by 俞亚楠 on 2015/10/9.
 */
public class Loginpage3 extends RelativeLayout  {
    private Context context;
    private AttributeSet attrs;
    private LinearLayout weixin_user_list_container;
    private ScrollView weixin_user_scroll;
    private LinearLayout weixin_user_rel;
    private RecyclerView recylcer;
    public static Map<String,Bitmap> map1=new HashMap<String,Bitmap>();
    private JSONArray arr_tp=null;
    private JSONArray arr_tx=null;
    private JSONObject obj_erweima=null;
    ArrayList<String> urls1 = new ArrayList<>();



    ImageLoader mImageLoader = null;
    RequestQueue mRequestQueue = null;
    public static ImageView shuaxin_button;
    private View mTagView = null;
    private MyAdapter mAdapter = null;
    private int mNextScreenFocusViewId = View.NO_ID;
    public Loginpage3(Context context) {
        super(context);
        this.context=context;
        LayoutInflater.from(context).inflate(R.layout.login_page3, this, true);
    }

    public Loginpage3(final Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context=context;
        this.attrs=attrs;
        LayoutInflater.from(context).inflate(R.layout.login_page3, this, true);
        shuaxin_button=(ImageView)findViewById(R.id.shuaxin_button);

        shuaxin();
        shuaxin_button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                shuaxin();
            }
        });

    }
    public void shuaxin(){

        weixin_user_list_container=(LinearLayout)findViewById(R.id.weixin_user_list_container);
        mRequestQueue = Volley.newRequestQueue(context.getApplicationContext());
        mImageLoader = new ImageLoader(mRequestQueue, new BitmapCache());
        JsonObjectRequest request = new JsonObjectRequest("http://61.191.46.214:8088/wanba/photo_ajax.jsp?userId="+ Util.getDeviceId(context), null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        try {
                            urls1.clear();
                            weixin_user_list_container.removeAllViews();
                            JSONArray arr=jsonObject.getJSONArray("userList");
                            arr_tx=arr;
                            arr_tp=jsonObject.getJSONArray("photos");
                            obj_erweima=jsonObject.getJSONObject("qrcode");
                            for (int j=0;j<arr_tp.length();j++){
                                JSONObject obj=arr_tp.getJSONObject(j);
                                urls1.add(obj.getString("imageUrl"));
                            }
                            for ( int i=0;i<arr.length();i++) {
                                WeinxinTouxiang v1 = new WeinxinTouxiang(context);
                                final CircleImageView iv=(CircleImageView)v1.findViewById(R.id.login_weixing_touxiang);
                                TextView tv=(TextView)v1.findViewById(R.id.login_weixin_name);
                                JSONObject obj=arr.getJSONObject(i);
                                tv.setText(obj.getString("userName"));
                                RequestQueue mQueue = Volley.newRequestQueue(context);

                                ImageRequest imageRequest = new ImageRequest(
                                        obj.getString("portraitUrl"),
                                        new Response.Listener<Bitmap>() {
                                            @Override
                                            public void onResponse(Bitmap response) {
                                                iv.setImageBitmap(response);
                                                map1.put( 8+ "touxiang", response);
                                            }
                                        }, 0, 0, Bitmap.Config.RGB_565, new Response.ErrorListener() {
                                    @Override
                                    public void onErrorResponse(VolleyError error) {
//                                    erweima_login.setImageResource(R.drawable.default_image);
                                    }
                                });
                                mQueue.add(imageRequest);
                                LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                                lp.leftMargin=20;
                                weixin_user_list_container.addView(v1,lp);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        }

        );
        mRequestQueue.add(request);

//        weixin_user_scroll=(ScrollView)findViewById(R.id.weixin_user_scroll);
//        weixin_user_rel=(LinearLayout)findViewById(R.id.weixin_user_rel);
//        int num=0;
//          for (int h=0;h<5;h++){
//              LinearLayout ll1=new LinearLayout(context);
//              ll1.setPadding(100,40,0,0);
//              weixin_user_rel.addView(ll1);
//              for (int i=0;i<5;i++){
//                  WeixinZhaopian_demo w1=new WeixinZhaopian_demo(context);
//                  FocusImageView weixin_demo_iv1=(FocusImageView)w1.findViewById(R.id.weixin_demo_iv1);
//                  View weixin_demo_zhezhao=(View)w1.findViewById(R.id.weixin_demo_zhezhao);
//                  XCRoundImageView weixin_demo_touxiang=(XCRoundImageView)w1.findViewById(R.id.weixin_demo_touxiang);
//                  TextView weixin_demo_shijian=(TextView)w1.findViewById(R.id.weixin_demo_shijian);
//                  ImageView weixin_demo_erweima=(ImageView)w1.findViewById(R.id.weixin_demo_erweima);
//                  LinearLayout.LayoutParams lp1=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//                  lp1.leftMargin=40;
//                  if(num==0){
//                      weixin_demo_zhezhao.setVisibility(GONE);
//                      weixin_demo_touxiang.setVisibility(GONE);
//                      weixin_demo_shijian.setVisibility(GONE);
//                      weixin_demo_iv1.setImageResource(R.drawable.ceshiweixin);
//                      weixin_demo_iv1.setFocusable(false);
//
//                  }
//                  ll1.addView(w1,lp1);
//                  num+=1;
//              }
//          }
        recylcer = (RecyclerView) findViewById(R.id.recyclerView);
        GridLayoutManager mgr=new GridLayoutManager(context,6);
        recylcer.setLayoutManager(mgr);
        recylcer.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                final int firstVisitableItemPosition = recyclerView.getChildPosition(
                        recyclerView.getChildAt(0));
                shuaxin_button.setFocusable(firstVisitableItemPosition == 0);
            }
        });
    }


    //继承自 RecyclerView.Adapter
    class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

        MyAdapter() {
        }

        //RecyclerView显示的子View
        //该方法返回是ViewHolder，当有可复用View时，就不再调用
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
            View v =  LayoutInflater.from(context).inflate(R.layout.weixin_zhaopian_demo, null);
            return new ViewHolder(v, urls1);
        }

        //将数据绑定到子View，会自动复用View
        @Override
        public void onBindViewHolder(final ViewHolder viewHolder, int i) {
//            viewHolder.textView.setText(data[i]);
            viewHolder.onBind(i);
            if(i==0){
                viewHolder.weixin_demo_zhezhao.setVisibility(GONE);
                viewHolder.weixin_demo_touxiang.setVisibility(GONE);
                viewHolder.weixin_demo_shijian.setVisibility(GONE);
                viewHolder.weixin_demo_shijian.setText("");
                viewHolder.weixin_demo_iv1.setImageResource(R.drawable.ceshiweixin);
                viewHolder.weixin_demo_iv1.setFocusable(false);
//                ImageRequest imageRequest = null;
                try {
//                    imageRequest = new ImageRequest(
//                            obj_erweima.getString("img"),
//                            new Response.Listener<Bitmap>() {
//                                @Override
//                                public void onResponse(Bitmap response) {
//                                    viewHolder.weixin_demo_erweima.setImageBitmap(response);
//                                    map1.put( 8+ "erweima", response);
//                                }
//                            }, 0, 0, Bitmap.Config.RGB_565, new Response.ErrorListener() {
//                        @Override
//                        public void onErrorResponse(VolleyError error) {
//    //                                    erweima_login.setImageResource(R.drawable.default_image);
//                        }
//                    });
                    if(obj_erweima!=null){
                        mImageLoader.get(obj_erweima.getString("img"), ImageLoader.getImageListener(
                                        viewHolder.weixin_demo_erweima, 0, 0),
                                viewHolder.weixin_demo_erweima.getWidth(),
                                viewHolder.weixin_demo_erweima.getHeight(),
                                ImageView.ScaleType.CENTER_CROP);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
//                mRequestQueue.add(imageRequest);
                viewHolder.weixin_demo_touxiang.setImageResource(R.drawable.fittime_guangbiao_tm);
            }else {
                viewHolder.weixin_demo_zhezhao.setVisibility(VISIBLE);
                viewHolder.weixin_demo_touxiang.setVisibility(VISIBLE);
                viewHolder.weixin_demo_shijian.setVisibility(VISIBLE);
                try {
                    JSONObject object=arr_tp.getJSONObject(i - 1);
                    viewHolder.weixin_demo_shijian.setText(object.getString("datetime"));
                    String url=object.getString("img");
                    String userId=object.getString("userId");
                    String TX_URL=null;
                    for(int a=0;a<arr_tx.length();a++) {
                        JSONObject tx = arr_tx.getJSONObject(a);
                        if (tx.getString("userId").equals(userId)) {
                            TX_URL = tx.getString("portraitUrl");
                        }
                    }

//                    ImageRequest imageRequest = new ImageRequest(
//                            TX_URL,
//                            new Response.Listener<Bitmap>() {
//                                @Override
//                                public void onResponse(Bitmap response) {
//                                    viewHolder.weixin_demo_touxiang.setImageBitmap(response);
//                                    map1.put( 8+ "TOUXIANG", response);
//                                }
//                            }, 0, 0, Bitmap.Config.RGB_565, new Response.ErrorListener() {
//                        @Override
//                        public void onErrorResponse(VolleyError error) {
////                                    erweima_login.setImageResource(R.drawable.default_image);
//                        }
//                    });
//                    mRequestQueue.add(imageRequest);
//
//                    ImageRequest imageRequest1 = new ImageRequest(
//                           url,
//                            new Response.Listener<Bitmap>() {
//                                @Override
//                                public void onResponse(Bitmap response) {
//                                    viewHolder.weixin_demo_iv1.setImageBitmap(response);
//                                    map1.put( 8+ "zhaopian", response);
//                                }
//                            }, 0, 0, Bitmap.Config.RGB_565, new Response.ErrorListener() {
//                        @Override
//                        public void onErrorResponse(VolleyError error) {
////                                    erweima_login.setImageResource(R.drawable.default_image);
//                        }
//                    });
//                    mRequestQueue.add(imageRequest1);
//                    viewHolder.weixin_demo_iv1.setImageResource(R.drawable.fittime_guangbiao_tm);
                    if (TX_URL != null) {
                        mImageLoader.get(TX_URL, ImageLoader.getImageListener(
                                viewHolder.weixin_demo_touxiang, 0, 0),
                                viewHolder.weixin_demo_touxiang.getWidth(),
                                viewHolder.weixin_demo_touxiang.getHeight(),
                                ImageView.ScaleType.CENTER_CROP);
                    }
                    mImageLoader.get(url, ImageLoader.getImageListener(
                            viewHolder.weixin_demo_iv1, 0, 0),
                            viewHolder.weixin_demo_iv1.getWidth(),
                            viewHolder.weixin_demo_iv1.getHeight(),
                            ImageView.ScaleType.CENTER_CROP);
                }catch (JSONException e){
                    e.printStackTrace();
                }

                viewHolder.weixin_demo_iv1.setFocusable(true);
                viewHolder.weixin_demo_erweima.setImageResource(R.drawable.fittime_guangbiao_tm);
//                if(i==1){
//                    xiangce_iv1=viewHolder.weixin_demo_iv1;
//                }
//                if(i==2){
//                    xiangce_iv2=viewHolder.weixin_demo_iv1;
//                }
//                if(i==3){
//                    xiangce_iv3=viewHolder.weixin_demo_iv1;
//                }
//                if(i==4){
//                    xiangce_iv4=viewHolder.weixin_demo_iv1;
//                }
//                if(i==5){
//                    xiangce_iv5=viewHolder.weixin_demo_iv1;
//                }

            }

            if (i > 0 && i < 6 && mTagView != null) {
                viewHolder.weixin_demo_zhezhao.setNextFocusUpId(mTagView.getId());
                viewHolder.weixin_demo_touxiang.setNextFocusUpId(mTagView.getId());
                viewHolder.weixin_demo_shijian.setNextFocusUpId(mTagView.getId());
                viewHolder.weixin_demo_iv1.setNextFocusUpId(mTagView.getId());
            } else {
                viewHolder.weixin_demo_zhezhao.setNextFocusUpId(View.NO_ID);
                viewHolder.weixin_demo_touxiang.setNextFocusUpId(View.NO_ID);
                viewHolder.weixin_demo_shijian.setNextFocusUpId(View.NO_ID);
                viewHolder.weixin_demo_iv1.setNextFocusUpId(View.NO_ID);

            }

            if (i == 1) {
                viewHolder.weixin_demo_iv1.setNextFocusLeftId(mNextScreenFocusViewId);
            } else {
                viewHolder.weixin_demo_iv1.setNextFocusLeftId(View.NO_ID);
            }

        }

        //RecyclerView显示数据条数
        @Override
        public int getItemCount() {
            if(arr_tp!=null){
                return arr_tp.length()+1;
            }
            else{
                return 1;
            }
        }

        //自定义的ViewHolder,减少findViewById调用次数
        class ViewHolder extends RecyclerView.ViewHolder {

            FocusImageView weixin_demo_iv1;
            View weixin_demo_zhezhao;
            CircleImageView weixin_demo_touxiang;
            TextView weixin_demo_shijian;
            ImageView weixin_demo_erweima;
            MyItemClickListener mListener;
            //在布局中找到所含有的UI组件
            public ViewHolder(View itemView, ArrayList<String> urls) {
                super(itemView);
                weixin_demo_iv1=(FocusImageView)itemView.findViewById(R.id.weixin_demo_iv1);
                weixin_demo_zhezhao=(View)itemView.findViewById(R.id.weixin_demo_zhezhao);
                weixin_demo_touxiang=(CircleImageView)itemView.findViewById(R.id.weixin_demo_touxiang);
                weixin_demo_shijian=(TextView)itemView.findViewById(R.id.weixin_demo_shijian);
                weixin_demo_erweima=(ImageView)itemView.findViewById(R.id.weixin_demo_erweima);
                mListener = new MyItemClickListener();
                mListener.urls = urls;
                weixin_demo_iv1.setOnClickListener(mListener);
            }

            public void onBind(int position) {
                mListener.position = position-1;
            }

        }

    }
    public class MyItemClickListener implements OnClickListener {

        int position;
        ArrayList<String> urls = urls1;

        /**
         * Called when a view has been clicked.
         *
         * @param v The view that was clicked.
         */
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setClass(context, AlbumFullScreenActivity.class);
            intent.putExtra("position", this.position);
            intent.putExtra("urls", this.urls);
            context.startActivity(intent);
        }
    }

    public static void onActivityDestory() {
        Iterator iter = map1.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next(); Object key = entry.getKey();
            Object val = entry.getValue();
            Bitmap a=(Bitmap)val;
            a.recycle();
        }
        System.gc();
    }

    public void setTagView(View v) {
        mTagView = v;
    }

    public void setNextScreenFocusViewId(int id) {
        mNextScreenFocusViewId = id;
    }

    public void init() {
        mAdapter = new MyAdapter();
        recylcer.setAdapter(mAdapter);
    }


}
